﻿define([
    'dojo/on',
    'dojo/dom',
    'dojo/_base/array',
    'dojo/_base/declare',
    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplateMixin',
    'dojo/_base/lang',
    'dojo/topic',
    'dijit/registry',
    'dojo/promise/all',
    'dojo/dom-construct',
    'esri/geometry/Extent',
    'esri/symbols/PictureMarkerSymbol',
    'esri/geometry/Point',
    'esri/graphic',
    'esri/layers/GraphicsLayer',
    'esri/symbols/jsonUtils',
    'esri/graphicsUtils',
    'esri/tasks/query',
    'esri/tasks/QueryTask',
    'esri/tasks/FindTask',
    'esri/tasks/FindParameters',
    'esri/SpatialReference',
    'esri/InfoTemplate',
    'dojo/text!./Address/templates/Address.html',
    'xstyle/css!./Address/css/Address.css',
    'dijit/form/Button',
    'dojo/domReady!'

], function (on, dom, array, declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, lang, topic, registry, all,
             domConstruct, Extent, PictureMarkerSymbol, Point, Graphic, GraphicsLayer, symbolUtils, graphicsUtils, Query, QueryTask, FindTask, FindParameters, SpatialReference, InfoTemplate, template) {

    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        templateString: template,
        widgetsInTemplate: true,
        sp: null,
        geometries2search: [],
        zoomExtentFactor: 1.5,
        queryID: 0,
        ids: [],
        objectiidfield: null,
        map: null,
        defaultResultsSymbols: {
            point: {
                type: 'esriSMS',
                style: 'esriSMSCircle',
                size: 25,
                color: [0, 255, 255, 32],
                angle: 0,
                xoffset: 0,
                yoffset: 0,
                outline: {
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: [0, 255, 255, 255],
                    width: 2
                }
            },
            polyline: {
                type: 'esriSLS',
                style: 'esriSLSSolid',
                color: [0, 255, 255, 255],
                width: 3
            },
            polygon: {
                type: 'esriSFS',
                style: 'esriSFSSolid',
                color: [0, 255, 255, 32],
                outline: {
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: [0, 255, 255, 255],
                    width: 3
                }
            }
        },
        defaultSelectionSymbols: {
            point: {
                type: 'esriSMS',
                style: 'esriSMSCircle',
                size: 25,
                color: [4, 156, 219, 32],
                angle: 0,
                xoffset: 0,
                yoffset: 0,
                outline: {
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: [4, 156, 219, 255],
                    width: 2
                }
            },
            polyline: {
                type: 'esriSLS',
                style: 'esriSLSSolid',
                color: [4, 156, 219, 255],
                width: 3
            },
            polygon: {
                type: 'esriSFS',
                style: 'esriSFSSolid',
                color: [4, 156, 219, 32],
                outline: {
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: [4, 156, 219, 255],
                    width: 3
                }
            }
        },

        postCreate: function () {
            this.inherited(arguments);
            this.sp = new SpatialReference({"wkt": 'PROJCS["shanghaicity",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",-3457147.81],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",121.2751921],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]'});
            map = this.map;
            topic.subscribe('address/clear', lang.hitch(this, 'clearAddress'));
            on(this.addressipt, "keyup", lang.hitch(this, "enterPress"));
        },
        enterPress: function (e) {
            var e = e || window.event;
            if (e.keyCode == 13) {
                this.clickHandler();
            }
        },
        clickHandler: function () {
            if (document.getElementById("addressipt").value == "") {
                dojo.empty("resultlist");
                var dd = dojo.create("div", {innerHTML: "<div style='border-bottom:1px solid #87CEFA'><a href='javascript:void(0)' class='list-group-item' ><h5 class='list-group-item-heading' >请输入要查询的地点、门牌或道路。<p class='list-group-item-text'></p></a></div>"});
                var resultlist = dojo.byId("resultlist");
                domConstruct.place(dd, resultlist, "frist");
                return;
            }
            map = this.map;
            var th = this;
            dojo.xhrGet({
                url: "http://10.207.204.29/OneMapServer/rest/services/address_p/aS_CH.asmx/ASCH_AddressSearch?vSearch_word=" + document.getElementById("addressipt").value + "&vResult_count=10&token=" + GLOBAL_TOKEN,
                handleAs: "xml",
                timeout: 5000,
                load: function (response, ioArgs) {
                    if (response.getElementsByTagName("DZ_Result")[0].children.length == 0 || response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("Result_Flag")[0].textContent == "0") {
                        dojo.empty("resultlist");
                        var dd = dojo.create("div", {innerHTML: "<div style='border-bottom:1px solid #87CEFA'><a href='javascript:void(0)' class='list-group-item' ><h5 class='list-group-item-heading' >在<b>上海市</b>范围内未找到相关地点。</h5><p class='list-group-item-text'></p></a></div>"});
                        var resultlist = dojo.byId("resultlist");
                        domConstruct.place(dd, resultlist, "frist");
                        return;
                    }

                    var addressresult = response.getElementsByTagName("DZ_Result")[0].getElementsByTagName("DZ_Table")[0].children[1].children[0].children;
                    if (addressresult.length > 0) {
                        dojo.empty("resultlist");
                        map.graphics.clear();

                        for (var i = 0; i < addressresult.length; i++) {
                            var item = addressresult[i];
                            var attr = new Object();
                            var infoCont = "";
                            //统一名称
                            var addname = "";
                            if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null)
                                addname = item.getElementsByTagName("POI")[0].textContent;
                            else if (null != item.getElementsByTagName("ROAD1")[0] && item.getElementsByTagName("ROAD1")[0].textContent != null)
                                addname = item.getElementsByTagName("ROAD1")[0].textContent;
                            else if (null != item.getElementsByTagName("ADDRESS")[0] && item.getElementsByTagName("ADDRESS")[0].textContent != null)
                                addname = item.getElementsByTagName("ADDRESS")[0].textContent;

                            var addtype = "";
                            if (null != item.getElementsByTagName("CLS")[0] && item.getElementsByTagName("CLS")[0].textContent != null)
                                addtype = item.getElementsByTagName("CLS")[0].textContent;
                            else if (null != item.getElementsByTagName("POI")[0] && item.getElementsByTagName("POI")[0].textContent != null)
                                addtype = "POI";
                            else
                                addtype = "其他";

                            var area = "";
                            if (null != item.getElementsByTagName("REGION_QX")[0] && item.getElementsByTagName("REGION_QX")[0].textContent != null)
                                area = item.getElementsByTagName("REGION_QX")[0].textContent;
                            else
                                area = "上海市";


                            attr["名称"] = addname;
                            attr["类型"] = addtype;
                            attr["区县"] = area;

                            var dd = dojo.create("div", {innerHTML: "<div style='border-bottom:1px solid #87CEFA'><a href='javascript:void(0)' class='list-group-item' ><p><img src='images/marker/" + (i + 1) + ".png' alt='单击选中地址' /><span   >" + addname + "</span></p><p class='list-group-item-text' style='color:gray'>" + area + ": " + attr["类型"] + "</p></a></div>"});
                            var resultlist = dojo.byId("resultlist");
                            domConstruct.place(dd, resultlist, "last");

                            var sms = new PictureMarkerSymbol("images/marker/" + (i + 1) + ".png", 19, 27);
                            var pt = new Point(Number(item.getElementsByTagName("POINT_X")[0].textContent), Number(item.getElementsByTagName("POINT_Y")[0].textContent), map.spatialReference);

                            infoCont += "<b>类型" + ":</b> " + attr["类型"] + " <br/>";
                            infoCont += "<b>区县" + ":</b> " + area + " <br/>";

                            var infoTemplate = new InfoTemplate("<b>" + addname + "</b>", infoCont);
                            var graphic = new Graphic(pt, sms, attr, infoTemplate);
                            map.graphics.add(graphic);

                            //闭包
                            (function (arg, arg2, g) {

                                on(dd, "click", function () {

                                    var center = new esri.geometry.Point(arg.x, arg.y, map.spatialReference);
                                    //显示info
                                    map.infoWindow.hide();
                                    map.infoWindow.setContent(g.getContent());
                                    map.infoWindow.setTitle(g.getTitle());
                                    map.infoWindow.show(g.geometry);
                                    map.centerAndZoom(center, 7);

                                });
                            })(pt, dd, graphic);
                        }
                    }
                },
                // Event handler on errors:
                error: function (response, ioArgs) {
                }
            });

        },
        zoomToGraphics: function (graphics) {
            var zoomExtent = null;
            if (graphics.length > 1) {
                zoomExtent = graphicsUtils.graphicsExtent(graphics);
            } else if (graphics.length === 1) {
                zoomExtent = this.getExtentFromGraphic(graphics[0]);
            }
            if (zoomExtent) {
                this.setMapExtent(zoomExtent);
            }
        },
        setMapExtent: function (extent) {
            this.map.setExtent(extent.expand(this.zoomExtentFactor));
        },
        getExtentFromGraphic: function (graphic) {
            var extent = null;
            switch (graphic.geometry.type) {
                case 'point':
                    extent = this.getExtentFromPoint(graphic);
                    break;
                default:
                    extent = graphicsUtils.graphicsExtent([graphic]);
                    break;
            }
            return extent;
        },
        clearAddress: function (results) {
            dojo.empty("resultlist");
            map.graphics.clear();
            map.infoWindow.hide();
        },
        getExtentFromPoint: function (point) {
            var sz = this.pointExtentSize; // hack
            var pointGeometry = point.geometry;
            return new Extent({
                'xmin': pointGeometry.x - sz,
                'ymin': pointGeometry.y - sz,
                'xmax': pointGeometry.x + sz,
                'ymax': pointGeometry.y + sz,
                'spatialReference': {
                    wkid: this.spatialReference
                }
            });
        },
        setGraphicSymbol: function (graphic, isSelected) {
            var symbol = isSelected ? this.graphicsSymbols.selectionSymbols[graphic.geometry.type] : this.graphicsSymbols.resultsSymbols[graphic.geometry.type];
            graphic.setSymbol(symbol);
        },
        addResultsToGraphicsLayer: function () {
            var unique = 0;
            this.graphicsLayer.clear();
            array.forEach(
                this.results.features, function (result) {
                    //result.id = unique;
                    //result.feature.storeid = result.id;
                    //unique++;
                    this.setGraphicSymbol(result, false);
                    this.graphicsLayer.add(result);
                }, this
            );
        },
        createGraphicsSymbols: function () {
            var graphicSymbols = {}, resultSymbolDefinitions, selectionSymbolDefinitions;
            resultSymbolDefinitions = lang.mixin(this.defaultResultsSymbols, this.resultsSymbols || {});
            graphicSymbols.resultsSymbols = {};
            graphicSymbols.resultsSymbols.point = symbolUtils.fromJson(resultSymbolDefinitions.point);
            graphicSymbols.resultsSymbols.polyline = symbolUtils.fromJson(resultSymbolDefinitions.polyline);
            graphicSymbols.resultsSymbols.polygon = symbolUtils.fromJson(resultSymbolDefinitions.polygon);
            selectionSymbolDefinitions = lang.mixin(
                this.defaultSelectionSymbols, this.selectionSymbols || {}
            );
            graphicSymbols.selectionSymbols = {};
            graphicSymbols.selectionSymbols.point = symbolUtils.fromJson(selectionSymbolDefinitions.point);
            graphicSymbols.selectionSymbols.polyline = symbolUtils.fromJson(selectionSymbolDefinitions.polyline);
            graphicSymbols.selectionSymbols.polygon = symbolUtils.fromJson(selectionSymbolDefinitions.polygon);
            return graphicSymbols;
        },
        createGraphicsLayerAndSymbols: function () {
            if (!this.graphicsLayer) {
                this.graphicsLayer = this.createGraphicsLayer();
            }
            if (!this.graphicsSymbols) {
                this.graphicsSymbols = this.createGraphicsSymbols();
            }
        },
        createGraphicsLayer: function () {
            var graphicsLayer = new GraphicsLayer({
                id: this.id + '_addGraphics',
                title: 'Find'
            });
            this.map.addLayer(graphicsLayer);
            return graphicsLayer;
        },
        onGraphicsLayerClick: function (event) {
            var zoomOnSelect = this.zoomOptions.select;
            this.zoomOptions.select = false;
            var row = this.resultsGrid.row(event.graphic.storeid);
            this.resultsGrid.select(row);
            this.resultsGrid.focus(row.element);
            row.element.focus();
            this.zoomOptions.select = zoomOnSelect;
        },
        clean: function () {
            if (this.graphicsLayer) {
                this.graphicsLayer.clear();
            }
        }
    });
});